<template>
  <div>
    <el-container class="subWidth">
     <el-header class="subheader" style="height: 48px;background-color: whitesmoke;margin: 2px;padding: 2px;border-radius: 5px;">
       <el-form :inline="true" class="demo-form-inline" label-position="left" label-width="80px">
         <el-form-item label="留言用户">
           <el-input v-model="searchQuery.userName" @keyup.enter="fetchItems"></el-input>
         </el-form-item>
         <el-form-item>
           <el-button type="primary"  @click="fetchItems">查询</el-button>
           <el-button type="primary"   @click="resetSearch">重置</el-button>
           <el-button type="primary"  @click="showAddDialog">新增</el-button>
         </el-form-item>
       </el-form>
     </el-header>
    <el-main id="tableContent">
      <el-table :data="message" style="width: 100%" show-header="true">
        <el-table-column type="selection" width="42" align="center"></el-table-column>
        <el-table-column prop="id" label="编号" width="45" align="center"></el-table-column>
        <el-table-column prop="userName" label="用户名称" width="150" align="center"></el-table-column>
        <el-table-column prop="messageContent" label="留言内容" width="230" align="center"></el-table-column>
        <el-table-column prop="release" label="发布时间" align="center" format="yyyy-MM-dd"></el-table-column>
        <el-table-column label="头像" align="center">
          <template slot-scope="scope">
            <img :src="scope.row.avater" style="width: 60px; height: 60px; object-fit: cover;"/>
          </template>
        </el-table-column>
        <el-table-column label="操作" fixed="right" width="200">
          <template slot-scope="scope">
            <el-button   plain type="danger" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

    </el-main>
      <!-- 新增/编辑商品对话框 -->
      <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="400px" height="300px">
        <div class="el-dialog-div">
          <el-form :model="currentMessage" label-width="80px">
            <el-form-item label="用户名称">
              <el-input v-model="currentMessage.userName"></el-input>
            </el-form-item>
            <el-form-item label="留言内容">
              <el-input v-model="currentMessage.messageContent"></el-input>
            </el-form-item>
            <el-form-item label="发布时间">
              <el-input v-model="currentMessage.release" type="time"></el-input>
            </el-form-item>
            <el-form-item label="头像">
              <el-input v-model="currentMessage.avater"></el-input>
            </el-form-item>
          </el-form>
        </div>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveForm">保存</el-button>
         </span>
      </el-dialog>
      <MyPagination :total="total"/>
    </el-container>
  </div>
</template>
<script>
import axios from "axios";
import MyPagination from "@/components/MyPagination.vue";
import '@/assets/add.css'

export default {
  components: {
    MyPagination
  },
  data() {
    return {
      searchQuery: {
        userName: ''
      },
      message: [],
      dialogVisible: false,
      dialogTitle: '新增留言',
      currentMessage: {
        id: null,
        userName: null,
        messageContent: null,
        release: null,
        avatar: null,
      },
      currentPage: 1, // 当前页码
      pageSize: 10, // 每页显示的条目数
      total: 0, // 总条目数
    }
  },
  methods: {
    toggleSelection(rows) {
      if (rows) {
        rows.forEach(row => {
          this.$refs.multipleTable.toggleRowSelection(row);
        });
      } else {
        this.$refs.multipleTable.clearSelection();
      }
    },

    // 在 methods 中定义的 add 方法，用于打开对话框并设置标题
    add(id) {
      this.dialogVisible = true;
      this.resetForm();
      if (id) {
        this.dialogTitle = '编辑留言';
        // 假设 findMessageById 是一个方法，用于根据 ID 查询商品详情
        this.findItemById(id);
      } else {
        this.dialogTitle = '新增留言';
      }
    },
    // 用于打开新增商品对话框的方法
    showAddDialog() {
      this.dialogVisible = true; // 设置对话框为可见
      this.resetForm(); // 重置表单
      this.dialogTitle = '新增留言'; // 设置对话框标题为“新增商品”
    },
    resetForm() {
      this.currentMessage = {
        id: null,
        userName: '',
        messageContent: '',
        release: null,
        avatar: '',
      }
    },
    findItemById(id) {
      axios.get(`/message/find/${id}`).then(response => {
        this.currentMessage = response.data;
      }).catch(error => {
        console.error("Error finding message by id:", error);
      });
    },
    // saveForm() {
    //
    //   if (this.currentMessage.id) {
    //     // 执行修改操作
    //     axios.put("/message/update").then(response => {
    //       // 使用 response 数据
    //       console.log('Update response:', response.data);
    //       this.dialogVisible = false;
    //       this.fetchItems();
    //       this.$message.success('留言信息更新成功');
    //     }).catch(error => {
    //       console.error("Error updating message:", error);
    //       this.$message.error('留言信息更新失败');
    //     });
    //   } else {
    //     // 执行新增操作
    //     axios.post("/message/add").then(response => {
    //       // 使用 response 数据
    //       console.log('Add response:', response.data);
    //       this.dialogVisible = false;
    //       this.fetchItems();
    //       this.$message.success('留言新增成功');
    //     }).catch(error => {
    //       console.error("Error adding message:", error);
    //       this.$message.error('留言新增失败');
    //     });
    //   }
    // },
    saveForm() {
      if (this.currentMessage.id) {
        // 执行修改操作
        axios.put("/message/update", this.currentMessage).then(response => {
          // 使用 response 数据
          console.log('Update response:', response.data);
          this.dialogVisible = false;
          this.fetchItems();
          this.$message.success('知识信息更新成功');
        }).catch(error => {
          console.error("Error updating knowledge:", error);
          this.$message.error('知识信息更新失败');
        });
      } else {
        // 执行新增操作
        axios.post("/message/add", this.currentMessage).then(response => {
          // 使用 response 数据
          console.log('Add response:', response.data);
          this.dialogVisible = false;
          this.fetchItems();
          this.$message.success('知识新增成功');
        }).catch(error => {
          console.error("Error adding knowledge:", error);
          this.$message.error('知识新增失败');
        });
      }

    },
    fetchItems() {
      const params = this.searchQuery.userName ? {userName: this.searchQuery.userName} : {};
      axios.get("/message/find", {params}).then(response => {
        this.message = response.data;
      }).catch(error => {
        console.error("Error fetching items:", error);
      });
    },
    resetSearch() {
      this.searchQuery.userName = '';
      this.fetchItems(); // 重置后重新获取所有商品列表
    },

    handleEdit(index, row) {
      this.dialogVisible = true; // 打开对话框
      this.dialogTitle = '反馈留言'; // 设置对话框标题
      // 将当前行的数据复制到 currentItem，用于在对话框中显示
      // 确保将 isDelete 和 isRecommed 转换为布尔值
      this.currentItem = {
        ...row,
        isDelete: row.isDelete === 1, // 将 1 转换为 true，0 转换为 false
        isRecommed: row.isRecommed === 1 // 将 1 转换为 true，0 转换为 false
      };
    },

    handleDelete(index, row) {
      axios.delete(`/message/delete/${row.id}`).then(response => {
        // 检查后端返回的响应数据
        if (response.data.success) { // 假设后端返回的数据包含一个 success 字段
          this.message.splice(index, 1);
          this.fetchItems();
          console.log("删除成功")
          this.$message.success('留言删除成功');
        }
      })
    }
  },
  mounted() {
    this.fetchItems(); // 页面加载时获取商品列表
  }
}
</script>

<style scoped>

</style>
